package com.jason.webserver.filter;

import org.apache.dubbo.common.Constants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;


@Activate(group = Constants.CONSUMER)
public class TpMonitorFilter implements Filter, Runnable {

    private List<String> list;

    public TpMonitorFilter() {
        list = new CopyOnWriteArrayList<>();
        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String name = invoker.getInterface().getName();
        long start = System.currentTimeMillis();
        Result result = null;
        try {
            result = invoker.invoke(invocation);
        } catch (RpcException e) {
            System.out.println("远程调用错误");
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        long time = end - start;
        list.add(name + "#" + time);
        return result;
    }

    @Override
    public void run() {
        while (true) {
            if (!CollectionUtils.isEmpty(list)) {
                System.out.println("打印耗时情况");
                for (String str : list) {
                    String[] strs = str.split("#");
                    System.out.println("接口" + strs[0] + "耗时：" + strs[1] + "ms");
                }
                list.clear();
                try {
                    Thread.sleep(5000);  //休眠5秒钟
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
